package collector.core.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Vector;

import org.apache.commons.lang.time.DurationFormatUtils;

/**
 * <pre>
 * Class : collector.util.DateUtil / DateUtil.java
 * 	Define Class Object : Date 관련 처리 Util Method 구현
 * <br>
 * </pre>
 * 
 * @author ytjeong / apexcns,Inc.
 * @version 1.0
 * @see javadoc
 * @since 2012. 9. 12.
 */
@SuppressWarnings("unchecked")
public class DateUtil {
	private static String defaultDateFormat = "yyyyMMdd";

	public static void setDefaultDateFormat(String dateFormat) {
		defaultDateFormat = dateFormat;
	}

	public static String getDefaultDateFormat() {
		return defaultDateFormat;
	}

	/**
	 * <pre>
	 * Method : DateUtil.now()
	 * 	현재 시각을 Date 형식으로 가져온다.
	 * <br>
	 * 	return type of Date
	 * <br>
	 * @return
	 * </pre>
	 */
	public static Date now() {
		return Calendar.getInstance().getTime();
	}

	/**
	 * <pre>
	 * Method : DateUtil.dateAdd()
	 * 	date의 주어진 달력 필드에 특정한 시간(amount)을 더하거나 뺀다
	 * <br>
	 * 	return type of Date
	 * <br>
	 * @param field	{ DATE, HOUR, MINUTE }
	 * @param amount
	 * @param date
	 * @return
	 * </pre>
	 */
	public static Date dateAdd(int field, int amount, Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(field, amount);

		return cal.getTime();
	}

	public static Date dateAdd(int field, int amount, String date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(
					DateUtil.getDefaultDateFormat());
			Date result = sdf.parse(date);
			result = DateUtil.dateAdd(field, amount, result);

			return result;
		} catch (Exception e) {
			return null;
		}
	}

	public static Date dateAdd(int field, int amount, String date,
			String inputDateFormat) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(inputDateFormat);
			Date result = sdf.parse(date);
			result = DateUtil.dateAdd(field, amount, result);

			return result;
		} catch (Exception e) {
			return null;
		}
	}

	public static String dateAddFormat(int field, int amount, Date date,
			String outputDateFormat) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(outputDateFormat);
			String formatDate = sdf.format(DateUtil
					.dateAdd(field, amount, date));

			return formatDate;
		} catch (Exception e) {
			return null;
		}
	}

	public static String dateAddFormat(int field, int amount, Date date) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(
					DateUtil.getDefaultDateFormat());
			String formatDate = sdf.format(DateUtil
					.dateAdd(field, amount, date));

			return formatDate;
		} catch (Exception e) {
			return null;
		}
	}

	public static String dateAddFormat(int field, int amount, String date,
			String dateFormat) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
			String formatDate = sdf.format(DateUtil.dateAdd(field, amount,
					date, dateFormat));

			return formatDate;
		} catch (Exception e) {
			return null;
		}
	}

	public static String dateAddFormat(int field, int amount, String date,
			String inputDateFormat, String outputDateFormat) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(outputDateFormat);
			String formatDate = sdf.format(DateUtil.dateAdd(field, amount,
					date, inputDateFormat));

			return formatDate;
		} catch (Exception e) {
			return null;
		}
	}

	/** 날짜 중간에 삽입된 기호들을 제거한다. */
	public static String trim(String str) {
		if (str == null)
			return null;
		return str.trim().replaceAll("[-/\\. :]", "");
	}

	/**
	 * 날짜 포맷 getFmtDateTime("20070901") => 2007-09-01
	 * getFmtDateTime("20070901121212") => 2007-09-01 12:12:12
	 */
	public static String getFmtDateTime(String str) {
		return getFmtDateTime(str, str == null ? 0 : str.length());
	}

	/**
	 * 날짜 포맷 sep : 년월일 별로 구분하기 위한 특수문자 입력 getFmtDateTime("20070901", "-") =>
	 * 2007-09-01 getFmtDateTime("20070901", ".") => 2007.09.01
	 */
	public static String getFmtDateTime(String str, String sep) {
		return getFmtDateTime(str, sep, str.length());
	}

	/**
	 * 날짜 포맷 outType : 출력형태 getFmtDateTime("20070901121212", 8) => 2007-09-01
	 */
	public static String getFmtDateTime(String str, int outType) {
		return getFmtDateTime(str, "-", str == null ? 0 : outType);
	}

	/**
	 * 날짜 포맷 sep : 년월일 별로 구분하기 위한 특수문자 입력 outType : 출력형태
	 * getFmtDateTime("20070901121212", 8) => 2007-09-01
	 */
	public static String getFmtDateTime(String str, String sep, int outType) {
		String ret = "";

		if (StringUtil.isEmpty(sep))
			sep = "";
		if (str == null || "".equals(str.trim()))
			return ret;
		if (outType == 0)
			outType = str.length();
		if (str.length() == 4)
			str += "0101";
		if (str.length() == 6)
			str += "01";
		Date date = ymdToDate(StringUtil.rpad(str, 14, "0"), "yyyyMMddHHmmss");

		return getFmtDateTime(date, sep, outType);
	}

	public static String getFmtDateTime(Date date, int outType) {
		return getFmtDateTime(date, "", outType);
	}

	public static String getFmtDateTime(Date date, String sep, int outType) {
		String ret = "";
		if (date == null)
			return ret;
		if (sep == null)
			sep = "";

		switch (outType) {
		case 4:
			ret = dateToYmd(date, "yyyy");
			break;
		case 6:
			ret = dateToYmd(date, "yyyy" + sep + "MM");
			break;
		case 8:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "dd");
			break;
		case 10:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "dd HH");
			break;
		case 12:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "dd HH:mm");
			break;
		case 14:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "dd HH:mm:ss");
			break;
		case 16:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "dd a HH:mm:ss");
			break;
		case 20:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "ddHH");
			break;
		case 22:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "ddHHmm");
			break;
		case 24:
			ret = dateToYmd(date, "yyyy" + sep + "MM" + sep + "ddHHmmss");
			break;
		case 104:
			ret = dateToYmd(date, "yyyy년");
			break;
		case 106:
			ret = dateToYmd(date, "yyyy년 M월");
			break;
		case 108:
			ret = dateToYmd(date, "yyyy년 M월 d일");
			break;
		case 110:
			ret = dateToYmd(date, "yyyy년 M월 d일 H시");
			break;
		case 111:
			ret = dateToYmd(date, "yyyy년 M월 d일 a h시");
			break;
		case 112:
			ret = dateToYmd(date, "yyyy년 M월 d일 H시 m분");
			break;
		case 113:
			ret = dateToYmd(date, "yyyy년 M월 d일 a h시 m분");
			break;
		case 114:
			ret = dateToYmd(date, "yyyy년 M월 d일 H시 m분 s초");
			break;
		case 115:
			ret = dateToYmd(date, "yyyy년 M월 d일 a h시 m분 s초");
			break;
		case 214:
			ret = dateToYmd(date, "yyyy년 M월 d일  HH:mm:ss");
			break;
		case 314:
			ret = dateToYmd(date, "yyyyMMddHHmmss");
			break;
		default:
			throw new IllegalArgumentException("표시할 수 없는 출력 포맷입니다.");
		}
		return ret;
	}

	public static String getFmtDateTime(Date date, int outType, String sep) {
		String ret = "";
		if (date == null)
			return ret;
		if (sep == null)
			sep = "";
		switch (outType) {
		case 4: // '\004'
			ret = dateToYmd(date, "yyyy");
			break;

		case 6: // '\006'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").toString());
			break;

		case 8: // '\b'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").append(sep).append("dd").toString());
			break;

		case 10: // '\n'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").append(sep).append("dd HH").toString());
			break;

		case 12: // '\f'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").append(sep).append("dd HH:mm").toString());
			break;

		case 14: // '\016'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").append(sep).append("dd HH:mm:ss").toString());
			break;

		case 16: // '\020'
			ret = dateToYmd(date, (new StringBuilder("yyyy")).append(sep)
					.append("MM").append(sep).append("dd a HH:mm:ss")
					.toString());
			break;

		case 104: // 'h'
			ret = dateToYmd(date, "yyyy\uB144");
			break;

		case 106: // 'j'
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4");
			break;

		case 108: // 'l'
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4 d\uC77C");
			break;

		case 110: // 'n'
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4 d\uC77C H\uC2DC");
			break;

		case 111: // 'o'
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4 d\uC77C a h\uC2DC");
			break;

		case 112: // 'p'
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4 d\uC77C H\uC2DC m\uBD84");
			break;

		case 113: // 'q'
			ret = dateToYmd(date,
					"yyyy\uB144 M\uC6D4 d\uC77C a h\uC2DC m\uBD84");
			break;

		case 114: // 'r'
			ret = dateToYmd(date,
					"yyyy\uB144 M\uC6D4 d\uC77C H\uC2DC m\uBD84 s\uCD08");
			break;

		case 115: // 's'
			ret = dateToYmd(date,
					"yyyy\uB144 M\uC6D4 d\uC77C a h\uC2DC m\uBD84 s\uCD08");
			break;

		case 214:
			ret = dateToYmd(date, "yyyy\uB144 M\uC6D4 d\uC77C  HH:mm:ss");
			break;

		case 314:
			ret = dateToYmd(date, "yyyyMMddHHmmss");
			break;

		default:
			throw new IllegalArgumentException(
					"\uD45C\uC2DC\uD560 \uC218 \uC5C6\uB294 \uCD9C\uB825 \uD3EC\uB9F7\uC785\uB2C8\uB2E4.");
		}
		return ret;
	}

	// 날짜 관련 Start ***************************************************//
	public static String dateToYmd(Date date, String formatOut) {
		String strOut = null;
		SimpleDateFormat formatter = null;
		try {
			formatter = new SimpleDateFormat(formatOut, Locale.KOREA);
			strOut = formatter.format(date);
		} catch (Exception e) {
			return strOut;
		}
		return strOut;
	}

	public static Date ymdToDate(String strIn, String formatIn, Locale locale) {
		Date date = null;
		SimpleDateFormat formatter = null;
		try {
			formatter = new SimpleDateFormat(formatIn, locale);
			date = formatter.parse(strIn);
		} catch (Exception e) {
			return date;
		}
		return date;
	}

	public static Date ymdToDate(String strIn, String formatIn) {
		return ymdToDate(strIn, formatIn, Locale.KOREA);
	}

	// ymdToYmd("20070704131610", "yyyyMMddHHmmss", "yyyy-MM-dd a hh:mm")
	public static String ymdToYmd(String strIn, String formatIn,
			String formatOut) {
		Date date = ymdToDate(strIn, formatIn);
		return date == null ? "" : dateToYmd(date, formatOut);
	}

	/** HTTP Header, Last-Modified format */
	private static String FMT_LAST_MODIFIED_STR = "E, dd MMM yyyy HH:mm:ss z";
	/** HTTP Header, Last-Modified format */
	private static SimpleDateFormat fmtLastModified = null;
	static {
		fmtLastModified = new SimpleDateFormat(FMT_LAST_MODIFIED_STR, Locale.US);
		fmtLastModified.setTimeZone(TimeZone.getTimeZone("GMT"));
	}

	/** make HTTP Header, Last-Modified */
	public static String getLastModifiedStr(long date) {
		return getLastModifiedStr(new Date(date));

	}

	/** make HTTP Header, Last-Modified */
	public static String getLastModifiedStr(Date date) {
		String strOut = null;
		try {
			strOut = fmtLastModified.format(date);
		} catch (Exception e) {
			return strOut;
		}
		return strOut;
	}

	/** parse HTTP Header, Last-Modified */
	public static Date getLastModifiedDate(String str) {
		Date data = null;
		try {
			data = fmtLastModified.parse(str);
		} catch (Exception e) {
			return data;
		}
		return data;
	}

	// 날짜 관련 End ***************************************************//

	public static String getFmtUptime(double uptime) {
		return getFmtUptime(uptime, "d", "h", "m");
	}

	public static String getFmtUptime(String uptime, String strDay,
			String strHour, String strMin) {
		try {
			return getFmtUptime(Double.parseDouble(uptime), strDay, strHour,
					strMin);
		} catch (Exception e) {
		}
		return null;
	}

	public static String getFmtDuration(double time, String strHour,
			String strMin, String strSec) {
		return getFmtDuration((long) time, strHour, strMin, strSec);
	}

	public static String getFmtDuration(long time, String strHour,
			String strMin, String strSec) {
		String format = "H" + strHour + "m" + strMin + "s" + strSec;
		return getFmtDuration(time, format);
	}

	public static String getFmtDuration(double time, String format) {
		return getFmtDuration((long) time, format);
	}

	public static String getFmtDuration(long time, String format) {
		return DurationFormatUtils.formatDuration(time, format, true);
	}

	// FIXME
	public static String getFmtUptime2(String uptime, String strDay,
			String strHour, String strMin) {
		try {
			return getFmtUptime(Double.parseDouble(uptime) / 1000d, strDay,
					strHour, strMin);
		} catch (Exception e) {
		}
		return null;
	}

	public static String getFmtUptime(double uptime, String strDay,
			String strHour, String strMin) {
		String retval = "";

		int days = (int) uptime / (60 * 60 * 24);
		int minutes, hours;

		if (days != 0) {
			retval += days + ((days > 1) ? strDay : strDay);
		}

		minutes = (int) uptime / 60;
		hours = minutes / 60;
		hours %= 24;
		minutes %= 60;

		if (hours != 0) {
			retval += hours + strHour + minutes + strMin;
		} else {
			retval += minutes + strMin;
		}

		return retval;
	}

	/**
	 * 날짜 포맷 getSplitDate("2007-09-01") => 20070901
	 * 
	 */
	public static String getSplitDate(String yyyymmdd) {
		String ymd = yyyymmdd.trim();
		if (ymd.length() == 7)
			return ymd.substring(0, 4) + ymd.substring(5, 7);
		else if (ymd.length() == 10)
			return ymd.substring(0, 4) + ymd.substring(5, 7)
					+ ymd.substring(8, 10);
		else
			return ymd;
	}

	/**
	 * 현재 시간이 from, to 에 포함되는지 여부 예)입력형태 20070901220103, 200709012 등..
	 */
	public static boolean isBetweenCurrDate(String from, String to) {
		Date currDate = new Date();
		return currDate.compareTo(parseDate(from)) >= 0
				&& currDate.compareTo(parseDate(to)) <= 0;
	}

	/** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(String from, String to) {
		return getBetweenDateTime(parseDate(from), parseDate(to));
	}

	/** 두 시간의 차이를 구한다. */
	public static long getBetweenDateTime(Date from, Date to) {
		return to.getTime() - from.getTime();
	}

	/** 두 시간의 차이를 구한다. (날짜) */
	public static int getBetweenDays(String from, String to) {
		// return Integer.parseInt(to.substring(0, 8)) -
		// Integer.parseInt(from.substring(0, 8));
		long gap = getBetweenDateTime(from, to);
		// long time = 1000; //1초
		// time *= 60; //1분
		// time *= 60; //1시간
		// time *= 24; //1일
		long time = 86400000;
		return (int) (gap / time);
	}

	/**
	 * 입력문자열을 Date객체로 리턴한다. 날짜입력형태 20070901220103, 200709012 등..
	 */
	public static Date parseDate(String str) {
		return ymdToDate(StringUtil.rpad(str, 14, "0"), "yyyyMMddHHmmss");
	}

	/** 윤년여부 */
	public static boolean isLeapYear(String str) {
		return new GregorianCalendar().isLeapYear(Integer.parseInt(str
				.substring(0, 4)));
	}

	/** 정상적인 날짜여부 */
	public static boolean isValidDate(String str) {
		str = StringUtil.rpad(str, 14, "0");
		return str.equals(dateToYmd(parseDate(str), "yyyyMMddHHmmss"));
	}

	/**
	 * 
	 * @param sDate
	 *            날짜 to
	 * @param eDate
	 *            날짜 From
	 * @param iFlag
	 *            1:일일 기준, 2:월 기준, "": 년기준
	 * @param iDel
	 *            년+"iDel"+월+"iDel"+일
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Vector getDates(String sDate, String eDate, String iFlag,
			String iDel) {
		Vector vDates = new Vector();

		try {
			int sYYYY = Integer.parseInt(sDate.substring(0, 4));
			int sMM = Integer.parseInt(sDate.substring(4, 6));
			int sDD = Integer.parseInt(sDate.substring(6, 8));

			int eYYYY = Integer.parseInt(eDate.substring(0, 4));
			int eMM = Integer.parseInt(eDate.substring(4, 6));
			int eDD = Integer.parseInt(eDate.substring(6, 8));

			Calendar startNow = Calendar.getInstance();
			startNow.set(sYYYY, sMM - 1, sDD);

			Calendar endNow = Calendar.getInstance();
			endNow.set(eYYYY, eMM - 1, eDD);

			long lST = startNow.getTime().getTime();
			long lET = endNow.getTime().getTime();
			long oneDay = (1000L * 60 * 60 * 24);

			if (iFlag.equals("1")) {
				for (long i = lST; i <= lET; i += oneDay, startNow.add(
						Calendar.DATE, 1)) {
					vDates.addElement(startNow.get(Calendar.YEAR)
							+ iDel
							+ (startNow.get(Calendar.MONTH) + 1 < 10 ? "0"
									+ (startNow.get(Calendar.MONTH) + 1) : ""
									+ (startNow.get(Calendar.MONTH) + 1))
							+ iDel
							+ (startNow.get(Calendar.DAY_OF_MONTH) < 10 ? "0"
									+ startNow.get(Calendar.DAY_OF_MONTH) : ""
									+ startNow.get(Calendar.DAY_OF_MONTH)));
				}

			} else if (iFlag.equals("2")) {
				for (int i = sYYYY; i <= eYYYY; i++) {
					for (int j = (i == sYYYY ? sMM : 1); j <= (i < eYYYY ? 12
							: eMM); j++) {
						vDates.addElement(i + iDel
								+ (j < 10 ? "0" + j : "" + j) + iDel + "01");
					}
				}
			} else {
				for (int i = sYYYY; i <= eYYYY; i++) {
					vDates.addElement(i + iDel + "01" + iDel + "01");
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return (vDates);

	}

	/**
	 * 현재의 날짜를 포멧에 맞게 변환 해준다.(한글포멧)
	 * 
	 * @param format
	 * @return
	 */
	public static String getCurrentDate(String format) {
		return getCurrentDate(format, Locale.KOREA);
	}

	/**
	 * 현재의 날짜를 포멧에 맞게 변환 해준다.
	 * 
	 * <pre>
	 * SimpleDateFormat Format Syntax
	 * G        era designator          (Text)              AD
	 * y        year                    (Number)            1996
	 * M        month in year           (Text & Number)     July & 07
	 * d        day in month            (Number)            10
	 * h        hour in am/pm (1~12)    (Number)            12
	 * H        hour in day (0~23)      (Number)            0
	 * m        minute in hour          (Number)            30
	 * s        second in minute        (Number)            55
	 * S        millisecond             (Number)            978
	 * E        day in week             (Text)              Tuesday
	 * D        day in year             (Number)            189
	 * F        day of week in month    (Number)            2 (2nd Wed in July)
	 * w        week in year            (Number)            27
	 * W        week in month           (Number)            2
	 * a        am/pm marker            (Text)              PM
	 * k        hour in day (1~24)      (Number)            24
	 * K        hour in am/pm (0~11)    (Number)            0
	 * z        time zone               (Text)              Pacific Standard Time
	 * '        escape for text         (Delimiter)
	 * ''       single quote            (Literal)           '
	 * </pre>
	 * 
	 * 예) WUtil.getCurrentDate("yyyy년 MM월 dd일") WUtil.getSvcLang("KR",
	 * WUtil.getCurrentDate("yyyy년 MM월 dd일"),
	 * WUtil.getCurrentDate("MM dd, yyyy")) WUtil.getCurrentFullDate("KR")
	 * 
	 * @param format
	 * @param loc
	 * @return
	 */
	public static String getCurrentDate(String format, Locale loc) {
		if (format == null || format.equals(""))
			return "";

		SimpleDateFormat formatter = new SimpleDateFormat(format, loc);
		return formatter.format(new Date());
	}

	/*
	 * fromDate - toDate
	 */
	public static final int getDateGap(String toDate, String fromDate,
			String format) {
		// long MpSec = 1000;
		// long MpMin = 60*1000;
		// long MpHou = 60*60*1000;
		long MpDay = 24 * 60 * 60 * 1000;

		try {
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			Date to_Date = ((DateFormat) formatter).parse(toDate);
			Date from_Date = ((DateFormat) formatter).parse(fromDate);

			Calendar before = new GregorianCalendar();
			Calendar after = new GregorianCalendar();

			before.setTime(to_Date);
			after.setTime(from_Date);

			long millis = after.getTime().getTime()
					- before.getTime().getTime();
			long days = millis / MpDay;
			// long hours = millis / MpHou;
			// long minutes = millis / MpMin;
			// long seconds = millis / MpSec;
			// logger.debug("밀리초차이:"+millis);
			// logger.debug("초차이:"+seconds);
			// logger.debug("분차이:"+minutes);
			// logger.debug("시간차이:"+hours);
			/*
			 * logger.debug("날차이:"+days); logger.debug(days+"일 "
			 * +(millis%MpDay)/MpHou+"시간 " +((millis%MpDay)%MpHou)/MpMin+"분 "
			 * +(((millis%MpDay)%MpHou)%MpMin)/MpSec+"초 차이");
			 */
			return (int) days;
		} catch (Exception e) {
			return 0;
		}
	}

	public static final int getDateGap(String toDate, String fromDate,
			String format, String type) {
		long MpSec = 1000;
		long MpMin = 60 * 1000;
		long MpHou = 60 * 60 * 1000;
		long MpDay = 24 * 60 * 60 * 1000;

		try {
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			Date to_Date = ((DateFormat) formatter).parse(toDate);
			Date from_Date = ((DateFormat) formatter).parse(fromDate);

			Calendar before = new GregorianCalendar();
			Calendar after = new GregorianCalendar();

			before.setTime(to_Date);
			after.setTime(from_Date);

			long millis = after.getTime().getTime()
					- before.getTime().getTime();
			long days = millis / MpDay;
			long hours = millis / MpHou;
			long minutes = millis / MpMin;
			long seconds = millis / MpSec;
			// long hours = millis / MpHou;
			// long minutes = millis / MpMin;
			// long seconds = millis / MpSec;
			// logger.debug("밀리초차이:"+millis);
			// logger.debug("초차이:"+seconds);
			// logger.debug("분차이:"+minutes);
			// logger.debug("시간차이:"+hours);
			/*
			 * logger.debug("날차이:"+days); logger.debug(days+"일 "
			 * +(millis%MpDay)/MpHou+"시간 " +((millis%MpDay)%MpHou)/MpMin+"분 "
			 * +(((millis%MpDay)%MpHou)%MpMin)/MpSec+"초 차이");
			 */
			if (type.equals("DAY"))
				return (int) days;
			if (type.equals("HOUR"))
				return (int) hours;
			if (type.equals("MINUTE"))
				return (int) minutes;
			if (type.equals("SECOND"))
				return (int) seconds;
			else
				return (int) days;
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * <PRE>
	 * milli second의 값을 입력받은 format의 스트링으로 리턴한다..
	 * format에 대한 내용은 java.text.SimpleDateFormat class의 api를 참조.
	 * 사용예)
	 * String time = "1119410042";
	 * logger.debug("time = " + DateUtil.getDate(Long.parseLong(time) * 1000, "yyyyMMddHHmmss"));
	 * String millSecond = "1121925709715";
	 * logger.debug("time = " + DateUtil.getDate(Long.parseLong(millSecond), "yyyyMMddHHmmssS"));
	 * @param milliSecond
	 * @param format
	 * @return
	 * </PRE>
	 */
	public static final String getDate(long milliSecond, String format) {
		SimpleDateFormat dateFormat = null;
		Date date = null;
		String currDate = null;
		try {
			dateFormat = new SimpleDateFormat(format);
			date = new Date(milliSecond);
			currDate = dateFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dateFormat = null;
			date = null;
			format = null;
		}
		return currDate;
	}

	/**
	 * 1970년 01월 01일 부터의 Seconds 반환.
	 * 
	 * @param dateStr
	 * @param format
	 * @return
	 */
	public static long getSecondsFrom1970(String dateStr, String format) {
		long resVal = 0;
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);

		try {
			Date date = ((DateFormat) dateFormat).parse(dateStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			resVal = calendar.getTimeInMillis() / 1000;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resVal;
	}

	public static String timeToDHM(long duration, String strDay, String shour,
			String smin, String ssec) {
		long temp = duration / (1000 * 60 * 60 * 24);
		String res = temp + strDay;
		duration -= temp * (1000 * 60 * 60 * 24);
		temp = duration / (1000 * 60 * 60);
		res += temp + " hours and ";
		duration -= temp * (1000 * 60 * 60);
		temp = duration / (1000 * 60);
		res += temp + " minutes";
		duration -= temp * (1000 * 60);
		temp = duration / (1000);
		res += temp + " sec";
		return res;
	}

	public static String getDate(String check) {
		Date date = new Date();
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
		SimpleDateFormat yy = new SimpleDateFormat("yy");
		SimpleDateFormat mm = new SimpleDateFormat("MM");
		SimpleDateFormat dd = new SimpleDateFormat("dd");
		SimpleDateFormat HH = new SimpleDateFormat("HH");
		SimpleDateFormat mi = new SimpleDateFormat("mm");
		SimpleDateFormat ss = new SimpleDateFormat("ss");
		SimpleDateFormat ms = new SimpleDateFormat("SSS");
		String strdate = simpleDate.format(date);
		String strdatetime = datetime.format(date);
		String lYear = yyyy.format(date);
		String sYear = yy.format(date);
		String month = mm.format(date);
		String day = dd.format(date);
		String hour = HH.format(date);
		String minute = mi.format(date);
		String second = ss.format(date);
		String milisecond = ms.format(date);
		if (check.equals("yyyy"))
			return lYear;
		if (check.equals("yy"))
			return sYear;
		if (check.equals("mm"))
			return month;
		if (check.equals("dd"))
			return day;
		if (check.equals("hh"))
			return hour;
		if (check.equals("mi"))
			return minute;
		if (check.equals("ss"))
			return second;
		if (check.equals("ms"))
			return milisecond;
		if (check.equals("date"))
			return strdate;
		if (check.equals("yyyymmdd"))
			return (new StringBuilder(String.valueOf(lYear))).append(month)
					.append(day).toString();
		if (check.equals("yyyymm"))
			return (new StringBuilder(String.valueOf(lYear))).append(month)
					.toString();
		if (check.equals("yymmdd"))
			return (new StringBuilder(String.valueOf(sYear))).append(month)
					.append(day).toString();
		if (check.equals("yymm"))
			return (new StringBuilder(String.valueOf(sYear))).append(month)
					.toString();
		if (check.equals("hhmiss"))
			return (new StringBuilder(String.valueOf(hour))).append(minute)
					.append(second).toString();
		if (check.equals("datetime"))
			return strdatetime;
		if (check.equals("hhmissms"))
			return (new StringBuilder(String.valueOf(hour))).append(":")
					.append(minute).append(":").append(second).append(":")
					.append(milisecond).toString();
		if (check.equals("total"))
			return (new StringBuilder(String.valueOf(lYear))).append(month)
					.append(day).append(hour).append(minute).append(second)
					.append(milisecond).toString();
		else
			return "";
	}

	public static String getDate(long millis) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(millis);
		int yy = cal.get(1);
		int mm = cal.get(2) + 1;
		int dd = cal.get(5);
		StringBuffer sDate = new StringBuffer();
		sDate.append(yy);
		if (mm < 10)
			sDate.append("0").append(mm);
		else
			sDate.append(mm);
		if (dd < 10)
			sDate.append("0").append(dd);
		else
			sDate.append(dd);
		return sDate.toString();
	}

	public static String getFullDate(String gubun) {
		return (new StringBuilder(String.valueOf(getDate("yyyy"))))
				.append(gubun).append(getDate("mm")).append(gubun)
				.append(getDate("dd")).toString();
	}

	public static String getFullTime(String gubun) {
		return (new StringBuilder(String.valueOf(getDate("hh")))).append(gubun)
				.append(getDate("mi")).append(gubun).append(getDate("ss"))
				.toString();
	}

	public static String getDatetime() {
		String temp = (new StringBuilder(String.valueOf(getDate()))).append(
				getTime()).toString();
		return temp;
	}

	public static String getDate() {
		Calendar cal = Calendar.getInstance();
		int yy = cal.get(1);
		int mm = cal.get(2) + 1;
		int dd = cal.get(5);
		StringBuffer sDate = new StringBuffer();
		sDate.append(yy);
		if (mm < 10)
			sDate.append("0").append(mm);
		else
			sDate.append(mm);
		if (dd < 10)
			sDate.append("0").append(dd);
		else
			sDate.append(dd);
		return sDate.toString();
	}

	public static String getTime() {
		Calendar cal = Calendar.getInstance();
		int hh = cal.get(11);
		int mm = cal.get(12);
		int ss = cal.get(13);
		String hhh = null;
		String mmm = null;
		String sss = null;
		if (hh < 10)
			hhh = (new StringBuilder("0")).append(hh).toString();
		else
			hhh = (new StringBuilder()).append(hh).toString();
		if (mm < 10)
			mmm = (new StringBuilder("0")).append(mm).toString();
		else
			mmm = (new StringBuilder()).append(mm).toString();
		if (ss < 10)
			sss = (new StringBuilder("0")).append(ss).toString();
		else
			sss = (new StringBuilder()).append(ss).toString();
		String addTime = (new StringBuilder()).append(hhh).append(mmm)
				.append(sss).toString();
		return addTime;
	}

	public static long getTimelong() {
		return (System.currentTimeMillis() + 500L) / 1000L;
	}

	public static void main(String[] args) {
		// System.out.println(getFmtDuration(1199800, "H시 m분 s초"));

		Date d = DateUtil.now();

		System.out.println("현재시각 | " + d);
		System.out.println("	3일 증가 | " + dateAdd(Calendar.DATE, 3, d));
		System.out.println("	3시간 증가 | " + dateAdd(Calendar.HOUR, 3, d));
		System.out.println("	3분 증가 | " + dateAdd(Calendar.MINUTE, 3, d));
		System.out.println("	3초 증가 | " + dateAdd(Calendar.SECOND, 3, d));

		// d = new Date(Constants.currentTime);
		// System.out.println("기준시각 | "+d);
		// System.out.println("	1일 감소 | "+system.util.DateUtil.dateAddFormat(Calendar.DATE,
		// -1*1, Constants.simDf_Day.format(d), "yyyyMMddHHmmss"));
		// System.out.println("	기준시각 | "+new
		// Date(Constants.currentTime)+", 일자 | "+Constants.simDf_Day.format(d));
		// System.out.println("	일시분초 | "+Constants.simDf.format(d));
		// System.out.println("	일자 | "+Constants.simDf_Day.format(d));
		// System.out.println("	일시 | "+Constants.simDf_Hour.format(d));
		// System.out.println("	일시분 | "+Constants.simDf_Min.format(d));
	}
}
